/*
 * @Author: Smthie Smthie@qq.com
 * @Date: 2024-05-13 10:06:44
 * @LastEditors: Smthie Smthie@qq.com
 * @LastEditTime: 2024-05-31 18:02:35
 * @FilePath: \ProtocolTool\src\main\index.ts
 */
import { app, BrowserWindow, ipcMain, dialog, Notification, shell } from 'electron'
import { join, resolve } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { exec } from 'child_process'
import { globalShortcut } from 'electron'
import axios from 'axios'

const $appName = '地球物理专用设备网络通讯协议合规检测工具'
const iconPath = join(__dirname, '../../resources/icon.png')

// 单例锁
const gotTheLock = app.requestSingleInstanceLock()

// 主窗口页面加载URL
let $url
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
  $url = process.env['ELECTRON_RENDERER_URL']
} else {
  $url = join('file://', __dirname, '../renderer/index.html')
}
// 快捷键注册
function registryShortcut() {
  globalShortcut.register('CommandOrControl+J+K', () => {
    // 获取当前窗口
    BrowserWindow.getFocusedWindow()?.webContents.openDevTools()
  })
}
// jre路径，开发环境、生产环境
const jrePath = app.isPackaged
  ? join(resolve('./'), './resources/app.asar.unpacked/resources/jdk/bin')
  : join(resolve('./'), './resources/jdk/bin')
// jar包路径
const jarPath = app.isPackaged
  ? join(resolve('./'), './resources/app.asar.unpacked/resources/java.jar')
  : join(resolve('./'), './resources/java.jar')
// 启动Java进程
function launchJava() {
  // 运行jar包
  exec(`java -jar "${jarPath}"`, { cwd: jrePath }, (error) => {
    if (error) {
      console.error(`Jar err: ${error}`)
    }
    // JAR输出
    console.log('Jar out')
  })
}

// 杀死Java进程
async function killJava() {
  return axios
    .get('http://127.0.0.1:8082/server/getPid')
    .then((res) => {
      const pid = res.data.data
      console.log('pid', pid)
      exec(`taskkill /f /pid ${pid}`)
    })
    .catch(() => {
      console.log('kill')
      exec('taskkill /IM java.exe /F')
    })
}
// 创建主窗口
function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 640,
    show: false,
    autoHideMenuBar: true,
    icon: iconPath,
    resizable: false,
    maximizable: false,
    fullscreenable: false,
    titleBarStyle: 'hidden',
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 隐藏Mac红绿灯
  // mainWindow.setWindowButtonVisibility(false)

  // 显示窗口
  mainWindow.on('ready-to-show', () => {
    setTimeout(() => {
      mainWindow.show()
    }, 1000)
  })

  // 加载窗口内容
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  return mainWindow
}

app.whenReady().then(async () => {
  electronApp.setAppUserModelId('com.protocoltool')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  if (!gotTheLock) {
    // 已经有一个实例在运行，退出当前实例
    app.quit()
  } else {
    // 启动Java进程
    launchJava()
    // 创建主窗口
    const win = createWindow()
    // 监听第二个实例被运行时
    app.on('second-instance', () => {
      // 当有第二个实例被运行时，激活之前的实例并将焦点置于其窗口
      if (win) {
        if (win.isMinimized()) win.restore()
        win.focus()
      }
    })
  }

  // 注册快捷键
  if (app.isPackaged) {
    registryShortcut()
  }

  // 最小化
  ipcMain.on('minimize', (e) => {
    BrowserWindow.fromWebContents(e.sender)?.minimize()
  })
  // 关闭
  ipcMain.on('close', (e) => {
    BrowserWindow.fromWebContents(e.sender)?.close()
  })
  // 保存文件
  ipcMain.handle('dialog:saveFile', async (e, title, url, fileName) => {
    // 获取扩展名
    const ext = fileName.split('.').pop()
    const filters = [{ name: '', extensions: [ext] }]
    // 打开保存文件窗口
    const res = await dialog.showSaveDialog({
      title,
      defaultPath: fileName,
      filters
    })
    // 保存
    if (res.filePath) {
      const webContents = e.sender
      const filePath = res.filePath
      // 下载
      webContents.downloadURL(url)
      webContents.session.once('will-download', (_e, item) => {
        // 设置保存路径
        item.setSavePath(filePath)
        item.once('done', (_e, state) => {
          // 下载成功
          if (state === 'completed') {
            const notice = new Notification({
              title: $appName,
              body: '保存成功，点击打开文件。',
              icon: iconPath
            })
            // 显示通知
            notice.show()
            // 点击打开文件
            notice.once('click', () => {
              shell.openPath(filePath)
            })
          }
        })
      })
    }
  })
  // 重启Java进程
  ipcMain.handle('restartJava', (_e, pid) => {
    console.log('pid', pid)
    exec(`taskkill /f /pid ${pid}`, (error) => {
      if (error) {
        console.log('error', error)
      }
      // 启动Java进程
      console.log('launchJava')
      launchJava()
    })
  })

  type Win = {
    id: number
    path: string
  }
  // 活跃窗口列表
  const activeWin: Win[] = []
  // 新建窗口
  ipcMain.on('newWin', (_e, args) => {
    const { title, width, height, path } = args
    // 如果窗口存在则唤起
    const oldWin = activeWin.find((item) => item.path === path)
    if (oldWin) {
      BrowserWindow.fromId(Number(oldWin.id))?.focus()
      return
    }
    // 创建新窗口
    const win = new BrowserWindow({
      width,
      height,
      show: false,
      icon: iconPath,
      autoHideMenuBar: true,
      resizable: false,
      maximizable: false,
      fullscreenable: false,
      titleBarStyle: 'hidden',
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    })
    // 添加活跃窗口列表
    activeWin.push({
      id: win.id,
      path
    })
    // 窗口加载页面
    if (!path) {
      win.loadURL($url)
    } else {
      win.loadURL(`${$url}#${path}`)
    }
    // 页面渲染完成，显示窗口
    win.on('ready-to-show', () => {
      win.setTitle(title)
      win.show()
    })
    // 窗口关闭移除活跃窗口列表
    win.on('close', () => {
      activeWin.splice(activeWin.indexOf(path), 1)
    })
  })
})

app.on('window-all-closed', async () => {
  await killJava()
  app.quit()
})

app.on('will-quit', () => {
  globalShortcut.unregisterAll()
})
